// 用户相关的action
// import { User } from '@/types/data'
import type { UserResponse, UserProfileResponse, UserProfile, UserPhotoResponse } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { http } from '@/utils/http'

// 返回http的用户信息约束
// type UserResponse = {
//   message: string
//   data: User
// }

// 获取用户自己的信息
export const getUser = (): RootThunkAction => {
  return async dispatch => {
    // 发起请求获取数据
    const res = await http.get<UserResponse>('/user')
    // console.log(res)
    // 把数据交给 reducer
    dispatch({
      type: 'user/getUser',
      payload: res.data.data
    })
  }
}
export const getUserProfile = (): RootThunkAction => {
  return async dispatch => {
    const res = await http.get<UserProfileResponse>('/user/profile')
    const profile = res.data.data
    console.log('profile', profile)
    dispatch({ type: 'user/getUserProfile', payload: profile })
  }
}
// 更新用户profile
export const updateUserProfile = (userProfile: Partial<UserProfile>): RootThunkAction => {
  return async dispatch => {
    await http.patch('/user/profile', userProfile)
    // 更新用户profile
    dispatch({ type: 'user/updateProfile', payload: userProfile })
  }
}
// 更新用户头像
export const updateUserPhoto = (file: FormData): RootThunkAction => {
  return async dispatch => {
    // 把头像提交给服务器
    const res = await http.patch<UserPhotoResponse>('/user/photo', file)
    console.log('photo res', res)
    // 分发action
    dispatch({
      type: 'user/updateProfile',
      payload: { photo: res.data.data.photo }
    })
  }
}
